package com.stars.easyms.alarm.client.wechat.message;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>className: NewsMessage</p>
 * <p>description: 图文消息</p>
 *
 * @author caotieshuan
 * @version 1.5.0
 * @date 2019-12-20 16:21
 */
public class NewsMessage implements Message {

    /**
     * 一个图文消息支持1到8条图文，这里限制为1-5
     */
    public static final int MAX_ARTICLE_NUM = 5;
    public static final int MIN_ARTICLE_NUM = 1;

    private List<NewsArticle> articles = new ArrayList<>();

    public void addNewsArticle(NewsArticle newsArticle) {
        if (articles.size() >= MAX_ARTICLE_NUM) {
            throw new IllegalArgumentException("number of articles can't more than " + MAX_ARTICLE_NUM);
        }
        if (StringUtils.isBlank(newsArticle.getTitle())) {
            throw new IllegalArgumentException("title of article should not be blank");
        }
        if (StringUtils.isBlank(newsArticle.getUrl())) {
            throw new IllegalArgumentException("url of article should not be blank");
        }
        articles.add(newsArticle);
    }


    @Override
    public String toJsonString() {
        Map<String, Object> items = new HashMap<>(8);
        //消息类型，此时固定为news
        items.put("msgtype", "news");

        Map<String, Object> news = new HashMap<>(8);
        if (articles.size() < MIN_ARTICLE_NUM) {
            throw new IllegalArgumentException("number of articles can't less than " + MIN_ARTICLE_NUM);
        }
        news.put("articles", articles);
        items.put("news", news);
        return JSON.toJSONString(items);
    }

    @Override
    public Map<String, Object> toMessageMap() {
        Map<String, Object> items = new HashMap<>(8);
        //消息类型，此时固定为news
        items.put("msgtype", "news");

        Map<String, Object> news = new HashMap<>(8);
        if (articles.size() < MIN_ARTICLE_NUM) {
            throw new IllegalArgumentException("number of articles can't less than " + MIN_ARTICLE_NUM);
        }
        news.put("articles", articles);
        items.put("news", news);
        return items;
    }
}